﻿
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text.RegularExpressions;
namespace ResourceReportBuilder
{
    public class TypeReferenceCollection : BindingList<TypeReference>
    {
        public string ProjectPath { get; private set; }

        public TypeReferenceCollection(string projectPath)
        {
            ProjectPath = projectPath;
            SetClassList();
        }

        private void SetClassList()
        {
            List<TypeReference> list = new List<TypeReference>();

            string content = string.Empty;
            #region read class files from project
            List<string> csList = new List<string>();
            using (StreamReader sr = new StreamReader(ProjectPath))
            {
                content = sr.ReadToEnd();
            }
            Regex regex = new Regex(@"<Compile Include=\""(.*)\""[\s/>|>]", RegexOptions.IgnoreCase);
            string path = null;
            foreach (Match match in regex.Matches(content))
            {
                path = Path.Combine(Path.GetDirectoryName(ProjectPath), match.Groups[1].Value);
                if (!path.EndsWith(".cs"))
                {
                    continue;
                }
                if (!csList.Contains(path) && File.Exists(path))
                {
                    csList.Add(path);
                }
            }
            #endregion

            foreach (string csFile in csList)
            {
                using (StreamReader sr = new StreamReader(csFile))
                {
                    content = sr.ReadToEnd();
                }

                // find class namespace
                string ns = string.Empty;
                regex = new Regex(@"namespace[\s]+(.+?)[\s|\:|\r\n|\r|\n]", RegexOptions.IgnoreCase);
                if (regex.IsMatch(content))
                {
                    ns = regex.Match(content).Groups[1].Value;
                }

                //find class declarations
                regex = new Regex(@"^([\s|\t].+?)class[\s]+(.+?[^\s|^\:]*).+?$", RegexOptions.Multiline);
                //regex = new Regex(@"class.+?(\s?(.+?)[^\:]*).+?", RegexOptions.IgnoreCase);
                foreach (Match match in regex.Matches(content))
                {
                    TypeReference item = new TypeReference(ns, match.Groups[2].Value);
                    item.Filename = csFile;
                    if (!list.Contains(item))
                    {
                        list.Add(item);
                    }
                }
            }

            list.Sort();
            list.ForEach(item => base.Items.Add(item));
        }
    }
}
